package com.wpc.service;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wpc.context.Content;
import com.wpc.mapper.UserWxPageMapper;
import com.wpc.mapper.UserwxgzhMapper;
import com.wpc.model.UserGzh;
import com.wpc.model.UserWxPage;
import com.wpc.util.HttpUtil;

@Service("wxNewsService")
public class WxNewsService {

	@Value("${md5key}")
	private String md5key;
	
	@Value("${wxkeyurl}")
	private String wxkeyurl;
	
	@Autowired
	private FlushKeyTaskService flushKeyTaskService;

	@Autowired
	private UserwxgzhMapper userwxgzhMapper;
	
	@Autowired
	private UserWxPageMapper uwxPageMapper;

	/**
	 * 循环遍历每个公众号文章
	 * 启动程序，立马执行
	 * @throws InterruptedException
	 */
	public void ergodicNews(int start,int max) throws InterruptedException {
		List<UserGzh> gzhList = null;
		String httResult = "";
		while (true) {
			if (start >= max) {
				start = 0;
			}
			gzhList = userwxgzhMapper.userGzhList(start, 30);
			for (UserGzh gzh : gzhList) {
				if(Content.lock==1){
					flushKeyTaskService.flushKey(gzh.getUserid(),md5key,gzh.getGzhid(),wxkeyurl);
				}
				httResult = HttpUtil.apacheHttpGet(gzh.getBiz(), Content.uin, Content.WX_KEY);
				if (httResult.equals("-1")) {//key已经过期，需要获取
					if(Content.lock==1){
						flushKeyTaskService.flushKey(gzh.getUserid(),md5key,gzh.getGzhid(),wxkeyurl);
					}
					Thread.sleep(2000);//必须延迟500hao秒钟，不然将被封死
					httResult = HttpUtil.apacheHttpGet(gzh.getBiz(), Content.uin, Content.WX_KEY);
				}
				if (!httResult.equals("-1")) {
					jiexiNewsJson(httResult,gzh.getMsgid(),gzh.getGzhid());
				}
			}
			start += 30;
		}
	}
	/**
	 * 解析json，处理最新文章url，保存到数据库
	 * @param jsonStr
	 * @param maxmsgid
	 * @param gzhid
	 */
	private void jiexiNewsJson(String jsonStr,Long maxmsgid, Long gzhid) {
		JSONObject json = JSONObject.parseObject(jsonStr);
		JSONObject obJson,comm_info,app_msg_ext_info;
		JSONArray multi_app_msg_item_list;
		Long datetime,commid,newMaxId = null;
		String content_url,title;
		UserWxPage page=new UserWxPage();
		page.setGzhid(gzhid);
		long isdeleteold=0;
		if (json != null) {
			JSONArray jsonArr = json.getJSONArray("list");
			for (int i = 0; i < jsonArr.size(); i++) {
				obJson=(JSONObject)jsonArr.get(i);
				comm_info=obJson.getJSONObject("comm_msg_info");
				datetime=comm_info.getLong("datetime");
				datetime=datetime*1000;//不然就是1970年
				commid=comm_info.getLong("id");
				if(i==0){
					newMaxId=commid;
				}
				if(commid>maxmsgid){//当前微信上文章id大于数据库中最大id，则需要跟新
					if(obJson.containsKey("app_msg_ext_info")){
						app_msg_ext_info=obJson.getJSONObject("app_msg_ext_info");
						content_url=app_msg_ext_info.getString("content_url");
						title=app_msg_ext_info.getString("title");
						page.setMsgid(commid);
						page.setCreatedate(new Date(datetime));
						page.setPageurl(content_url);
						title=title.replaceAll("[^\\u0000-\\uFFFF]", "");
						page.setTitle(title);
						if(uwxPageMapper.getCountByTitle(gzhid, commid, title)==0){
							uwxPageMapper.saveWxPage(page);
							multi_app_msg_item_list=app_msg_ext_info.getJSONArray("multi_app_msg_item_list");
							if(multi_app_msg_item_list!=null && multi_app_msg_item_list.size()>0){
								for(int j=0;j<multi_app_msg_item_list.size();j++){
									obJson=multi_app_msg_item_list.getJSONObject(j);
									title=obJson.getString("title");
									title=title.replaceAll("[^\\u0000-\\uFFFF]", "");
									content_url=obJson.getString("content_url");
									page.setPageurl(content_url);
									page.setTitle(title);
									uwxPageMapper.saveWxPage(page);
								}
							}
						}
						isdeleteold=commid;
					}
				}else{
					break;
				}
			}
		}
		if(newMaxId>maxmsgid){
			userwxgzhMapper.updateMsgId(gzhid,newMaxId);
		}
		if(isdeleteold!=0){//如果有更新文章就删除老的
			uwxPageMapper.deleteOldPage(gzhid, isdeleteold);
		}
	}

	public static void main(String args[]) throws ParseException{
		Long datetime=1480756455l;
		System.out.println(new Date(datetime*1000));
	}
}
